package com.itheima.service;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Test {

    private UserMapper mapper;
    private SqlSession sqlSession;
    private InputStream is;
    User user = new User();

    @Before
    public void init() throws IOException {

        //加载核心配置文件
        is = Resources.getResourceAsStream("SqlMapperConfig.xml");

        //获取工厂链接
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        sqlSession = build.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);

    }

    @After
    public void a() throws IOException {
        sqlSession.commit();
        sqlSession.close();
        is.close();
    }

    //if判断
    @org.junit.Test
    public void findAll() {
        user.setId(1);
        user.setUsername("盖伦");
        user.setPassword("1234");
        List<User> list = mapper.findAll(user);
        for (User user : list) {
            System.out.println(list.size()+"---"+user);
        }
    }

    //foreach查询
    @org.junit.Test
    public void findById(){
        //定义一个Integer集合数组
        List<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        List<User> list = mapper.findById(ids);
        for (User user : list) {
            System.out.println(user);
        }
    }

    //foreach查询
    @org.junit.Test
    public void findById2(){
        //定义一个数组
        int[] ids = {1,2,3};
        List<User> list = mapper.findById2(ids);
        for (User user : list) {
            System.out.println(user);
        }
    }

    //set更改
    @org.junit.Test
    public void update(){
        user.setId(2);
        user.setUsername("炎凉");
        user.setPassword("2345");
        mapper.update(user);
    }

    @org.junit.Test
    public void save(){
        user.setUsername("炎凉");
        user.setPassword("2345");
        mapper.save(user);
    }
}
